<template>
  <view class="list">
    <!-- 顶部提示框：动态显示更新数量 -->
    <view class="tips" :class="{ 'tips-ani': tipShow }"
      >为您更新了{{ updateCount }}条数据</view
    >

    <!-- 商品列表：添加加载中占位 -->
    <uni-list v-if="cinemaList && cinemaList.length > 0">
      <uni-list-item
        title="优惠券"
        note=""
        v-for="(item, index) in cinemaList"
        :key="index"
        class="coupon-item"
      >
        <template v-slot:header>
          <view class="uni-thumb shop-picture">
            <image
              :src="item.imageUrl || '../../static/logo.png'"
              mode="aspectFill"
            ></image>
          </view>
        </template>
        <!-- 通过body插槽定义商品布局 -->
        <template v-slot:body>
          <view class="shop-info">
            <text class="title">{{ item.name }}</text>
            <!-- <text >地址：{{ item.address }}</text> -->
            <view class="bottom-box">
              <text class="price"><text>¥</text>{{ item.currentPrice }}</text>
              <view class="buy" @tap="goBuy(item)">点击购买</view>
            </view>
          </view>
        </template>
      </uni-list-item>
    </uni-list>

    <!-- 空状态提示 -->
    <view v-else-if="!loading" class="empty-tip">暂无商品数据</view>

    <!-- 加载中提示 -->
    <view v-else class="loading-tip">加载中...</view>

    <!-- 上拉加载组件 -->
    <uni-load-more
      v-if="options.status !== 'more'"
      :status="options.status"
      margin-top="20rpx"
    />
  </view>

  <!-- SKU弹窗组件 -->
  <vk-data-goods-sku-popup
    v-model="isShowSku"
    :localdata="localdata"
    :mode="mode"
    add-cart-background-color="#FFA868"
    buy-now-background-color="#27BA9B"
    ref="skuPopupRef"
    :actived-style="{
      color: '#27BA9B',
      borderColor: '#27BA9B',
      backgroundColor: '#E9F8F5',
    }"
    @buy-now="onBuyNow"
  />
</template>

<script>
import { getProductListAPI } from "@/services/goodsList.js";
import {
  SkuPopupEvent,
  SkuPopupInstance,
  SkuPopupLocaldata,
} from "@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup";
export default {
  components: {},
  data() {
    return {
      tipShow: false,
      cinemaList: null, // 初始为null（区分空数据）
      loading: false, // 加载中状态
      updateCount: 0, // 实际更新数量
      options: {
        status: "more", // more:可加载, loading:加载中, noMore:无更多
        pageNum: 1,
        pageSize: 10,
      },
      isShowSku: false,
      localdata: {
        _id: "003",
        name: "迪奥香水",
        goods_thumb:
          "https://res.lancome.com.cn/resources/2020/9/11/15998112890781924_920X920.jpg?version=20200917220352530",
        sku_list: [
          {
            _id: "006",
            goods_id: "003",
            goods_name: "迪奥香水",
            image:
              "https://res.lancome.com.cn/resources/2020/9/11/15998112890781924_920X920.jpg?version=20200917220352530",
            price: 19800,
            sku_name_arr: ["默认"],
            stock: 100,
          },
        ],
        spec_list: [
          {
            list: [
              {
                name: "默认",
              },
            ],
            name: "默认",
          },
        ],
      },
      mode: 3,
    };
  },
  computed: {
    selectArrText() {
      return (
        this.$refs.skuPopupRef?.selectArr?.join(" ").trim() || "请选择商品规格"
      );
    },
  },
  mounted() {
    // 初始加载：先显示本地数据，再请求接口更新（优化体验）
    this.initGoodsListData();
    uni.$on("list:refresh", this.onPullDownRefresh1);
    uni.$on("list:loadmore", this.onReachBottom1);
  },

  beforeDestroy() {
    // 销毁时移除监听，避免内存泄漏
    uni.$off("list:refresh", this.onPullDownRefresh1);
    uni.$off("list:loadmore", this.onReachBottom1);
  },
  methods: {
    // 加载数据（支持首次加载/下拉刷新/上拉加载）
    async initGoodsListData(isLoadMore = false) {
      // 上拉加载时标记状态
      if (isLoadMore) {
        this.options.status = "loading";
      } else {
        this.loading = true; // 首次/刷新时显示加载中
      }

      try {
        const res = await getProductListAPI({
          pageNum: this.options.pageNum,
          pageSize: this.options.pageSize,
        });

        const newData = res.data.rows || [];
        console.log(222, newData);

        // 处理数据：首次/刷新→覆盖，上拉→追加
        if (isLoadMore) {
          this.cinemaList = [...this.cinemaList, ...newData];
        } else {
          // 计算更新数量（对比本地数据与接口数据）
          this.updateCount = newData.length;
          this.cinemaList = newData;
          // 显示提示框（3秒后隐藏）
          if (this.updateCount > 0) {
            this.tipShow = true;
            setTimeout(() => (this.tipShow = false), 3000);
          }
        }

        // 更新分页状态：无更多数据时标记
        this.options.status =
          newData.length < this.options.pageSize ? "noMore" : "more";
      } catch (err) {
        console.error("商品数据加载失败：", err);
        uni.showToast({ title: "加载失败", icon: "none" });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh(); // 无论成功失败，停止下拉刷新
      }
    },

    // 立即购买：统一用 _id 跳转
    goBuy(item) {
      if (!item?.id) {
        uni.showToast({ title: "商品信息异常", icon: "none" });
        return;
      }

      this.localdata = {
        _id: item.id,
        name: item.name,
        goods_thumb: item.imageUrl,
        spec_list: [
          {
            list: [
              {
                name: "默认",
              },
            ],
            name: "默认",
          },
        ],
        sku_list: [
          {
            _id: item.id,
            goods_id: item.cinemaId,
            goods_name: item.name,
            image: item.imageUrl,
            price: parseFloat(item.currentPrice) * 100, // 注意：需要乘以 100
            stock: parseInt(item.stock),
            sku_name_arr: ["默认"],
          },
        ],
      };
      this.isShowSku = true;
    },

    // 上拉加载更多
    loadMore() {
      // 避免重复加载
      if (this.options.status !== "more" || this.loading) return;
      this.options.pageNum += 1; // 页码自增
      this.initGoodsListData(true); // 标记为上拉加载
    },

    // 立即购买
    onBuyNow(ev) {
      console.log(111, ev);

      uni.navigateTo({
        url: `/pagesOrder/create/createTicket?skuId=${ev._id}&count=${ev.buy_num}&productId=${ev.goods_id}`,
      });

      this.isShowSku = false;
    },

    // 下拉刷新：重置页码，重新加载第一页
    onPullDownRefresh1() {
      this.options.pageNum = 1;
      this.options.status = "more";
      this.initGoodsListData();
    },

    // 上拉加载：调用加载更多方法
    onReachBottom1() {
      this.loadMore();
    },
  },
};
</script>

<style lang="scss">
// 页面背景色
page {
  background-color: #efeff4;
  min-height: 100%;
}

.tips {
  color: #67c23a;
  font-size: 14px;
  line-height: 40px;
  text-align: center;
  background-color: #f0f9eb;
  height: 0;
  opacity: 0;
  transform: translateY(-100%);
  transition: all 0.3s;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999; // 确保在顶部显示
}

.tips-ani {
  transform: translateY(0);
  height: 40px;
  opacity: 1;
}

// 商品列表样式
.uni-list-item--waterfall {
  padding: 15rpx;
  background-color: #fff;
  margin-bottom: 15rpx;
  border-radius: 10rpx;
}
.shop-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
  margin-left: 10px;
  .title {
    font-size: 16px;
  }
  .bottom-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .price {
      color: red;
      font-size: 16px;
    }
    .buy {
      width: 100px;
      height: 30px;
      line-height: 30px;
      background-color: #27ba9b;
      color: #fff;
      text-align: center;
      border-radius: 5px;
    }
  }
}
.shop {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-left: 15rpx;
}

.shop-picture {
  width: 220rpx;
  height: 220rpx;
  border-radius: 8rpx;
  overflow: hidden; // 图片圆角裁剪
}

.shop-picture image {
  width: 100%;
  height: 100%;
}

.uni-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.button-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10rpx;
}

.shop-price {
  font-size: 28rpx;
  color: #ff5a5f;
}

.shop-price-text {
  font-size: 36rpx;
  font-weight: bold;
}

.shop-buy {
  width: 180rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #27ba9b;
  color: #fff;
  text-align: center;
  border-radius: 30rpx;
  font-size: 28rpx;
}

// 空状态/加载中提示
.empty-tip,
.loading-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 30rpx;
}
</style>
